<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT Web Client</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>
<body>
    <h1>MQTT Web Client</h1>
    <div id="message"></div>

    <script>
        // MQTT Broker URL and port
        const brokerUrl = 'ws://localhost:9001'; // WebSocket URL for MQTT
        const topicSubscribe = 'iot/devices/test/baina/allinone/ws';

        // Create a client instance
        const client = mqtt.connect(brokerUrl);

        client.on('connect', function () {
            console.log('Connected to MQTT Broker');
            client.subscribe(topicSubscribe, function (err) {
                if (!err) {
                    console.log('Subscribed to topic:', topicSubscribe);
                } else {
                    console.error('Failed to subscribe to topic:', err);
                }
            });
        });

        client.on('message', function (topic, message) {
            // message is Buffer
            const messageStr = message.toString();
            console.log('Received message:', messageStr);

            // 创建一个新的 <p> 标签
            const newParagraph = document.createElement('p');
            newParagraph.innerText = messageStr;

            // 将新的 <p> 标签添加到 <div id="message"> 中
            document.getElementById('message').appendChild(newParagraph);
        });

        client.on('error', function (err) {
            console.error('MQTT Error:', err);
        });
    </script>
</body>
</html>
